package org.maxgroundstation.simulation.service;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Iterator;

public class ServiceSenderUDP {
    
    // Data members
    private ServiceCommunicationUDP comm;
    
    /**
     * Constructor
     * @param comm the service communication UDP.
     */
    ServiceSenderUDP(ServiceCommunicationUDP comm) {
    	this.comm = comm;
    }
    
    /**
     * Sending a service post.
     * @param serviceID the service ID.
     * @param clientID the client ID.
     * @param data the post data.
     */
    void sendServicePost(String serviceID, String clientID, byte[] data) throws Exception {
    	ServiceDataFrame dataFrame = ServiceUtil.createDataFrame(serviceID, clientID, data);
    	
    	Iterator<ServiceDataFragment> i = dataFrame.getDataFragments().iterator();
        while (i.hasNext()) {
          	byte[] packetData = i.next().toPacketData();
           	//System.out.println("packetData length: " + packetData.length);
           	DatagramPacket packet = new DatagramPacket(packetData, packetData.length);
            	
           	UDPClient client = comm.getClient(clientID);
           	if (client != null) {
           		//System.out.println("client found for ID: " + clientID);
           		InetAddress address = client.getAddress();
           		//System.out.println("client address: " + address.getHostAddress());
           		int port = client.getPort();
           		//System.out.println("client port: " + port);
           		packet.setAddress(address);
               	packet.setPort(port);
               	
               	comm.getSocket().send(packet);
           	}
           	else {
           		System.out.println("client not found for ID: " + clientID);
           	}
        }
    }
}